package com.bl.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.bl.domain.Product;
import com.bl.domain.Store;
import com.bl.feignclient.StoreFeignClient;
import com.bl.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/product")
@RefreshScope // 动态刷新配置注解
public class ProductController {

    @Autowired
    private StoreFeignClient storeFeignClient;

    @Autowired
    private IProductService productService;

    @PutMapping("/add")
    public String add(@RequestBody Product product){
        try {
            productService.add(product);
            Store store = product.getStore();
            store.setProduct_id(product.getId());
            storeFeignClient.add(store);
            return  ("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ("添加失败");
        }
    }


     @GetMapping("/getById/{id}")
    @SentinelResource(value="product-getById",  // Sentnel 限流规则名称
            blockHandler = "demotionMethod" // 指定降级方法
    )
    public Product getById(@PathVariable("id") Long id){
        return  productService.getById(id);
    }
    // 降级方法
    public Product demotionMethod(@PathVariable("id") Long id, BlockException e){
        e.printStackTrace();
        return  new Product(-1L,"限流勒,慢点",null,null);
    }


}
